import express from "express"
import configData from "@/config/index";
import {RoutesInterface} from "@/interface/routesInterface";
import sequelize from "@/databases";
import bodyParser from "body-parser";
import {error} from "@/utils/responseUtils";

export default class App {
    app: express.Application
    port: number = configData.port
    passUrl = ['/v1/users/login', '/v1/users/register', '/v1/404', '/v1/users/loginout'];

    constructor(routes: RoutesInterface[]) {
        this.app = express()
        //url解码
        this.app.use(bodyParser.urlencoded({extended: true}))
        //讲数据转换为json格式
        this.app.use(bodyParser.json())
        this.app.all("*",(req,res,next)=>{
            res.header("Access-Control-Allow-Origin", "*"); // 所有 Origin 来源都允许
            res.header("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");
            res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
            res.header("X-Powered-By",' 3.2.1');
            res.header("Content-Type", "application/json;charset=utf-8");
            next();
        })
        this.initializeRoutes(routes)
        this.connectDatabase()
    }

    /**
     * 链接数据库
     * @private
     */
    private connectDatabase() {
        // 创建同步表   force = true  时会把存在的表先 drop 掉再创建, alter = true 同步字段
        sequelize.sync({
            force: false,
            alter: true
        }).then(() => {
        })
    }

    /**
     * 初始化路由
     * @param routes
     * @private
     */
    private initializeRoutes(routes: RoutesInterface[]) {

        for (const routesKey in routes) {
            this.app.use('', routes[routesKey].router)
        }

    }

    /**
     * 启动服务
     */
    public listen() {
        this.app.listen(this.port, () => {
            console.log(`http://localhost:${this.port}/v1/curriculum`)
        })
    }
}